<?php


namespace App\controllers\admin;


use App\controllers\Base;
use Consts\RedisKey;
use Helper\Config;
use Helper\Output;
use Helper\Mysql;
use Firebase\JWT\JWT;
use Helper\Redis;
use Helper\Reg;
use Middleware\AuthMiddleware;

class Role extends Base
{

    public function index($request, $response){

        $list = Mysql::getInstance()
            ->where('id',1,'!=')
            ->get('role');

        foreach ($list as &$item) {

            $item['authority'] = Mysql::getInstance()->where('id',explode(',',$item['authority_ids']),'in')->get('authority');
        }
        return Output::json(200,$list);

    }

    public function create($request, $response){

        $res = Mysql::getInstance()->insert('role',$request->post);
        if($res){
            return Output::json(200);
        }
        return Output::json(400);
    }


    public function edit($request, $response){

        $id = $request->post['id'];
        unset($request->post['id']);
        $res = Mysql::getInstance()->where('id',$id)->update('role',$request->post);
        if($res){

            Redis::getInstance()->set(RedisKey::user_authority_list($id),
                json_encode(AuthMiddleware::getInstance()->getAuthority($request->post['role_id']))
            );
            return Output::json(200);
        }
    }

}